package com.avic.rong.activity.product;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.BaseActivity;
import com.avic.rong.BuildConfig;
import com.avic.rong.R;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SDCardUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.customWedgit.SheetDialog;
import com.avic.rong.wedgit.permissionschecker.PermissionChecker;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.utils.AppUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import wendu.dsbridge.DWebView;
import wendu.dsbridge.OnReturnValue;

/**
 * 在线客服
 */
public class OnlineCServiceActivity extends BaseActivity {


    public static final String ARG_KEYWORD = "keyword";
    private static final int TAKE_CAMERA_PHOTO = 200;

    @BindView(R.id.webview)
    DWebView webView;

    @BindView(R.id.tuijian)
    TextView tuijian;

    private ValueCallback mUploadCallBack;
    private ValueCallback<Uri[]> mUploadCallBackAboveL;
    private SheetDialog sheetDialog;
    private PermissionChecker permissionChecker;
    private String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private String cameraPath;



    @Override
    protected int getContentViewId() {
        return R.layout.activity_pdf_reader;
    }


    @Override
    protected void initView() {

        ButterKnife.bind(this);
        tuijian.setText("在线服务");

        String keyWords = getIntent().getStringExtra(ARG_KEYWORD);
//        sharePreferenceUtils =  SharePreferenceUtils.getInstance(this);
        webView.addJavascriptObject(this, null);


        permissionChecker = new PermissionChecker(OnlineCServiceActivity.this);
//        String url = AppUtils.BASE_URL + "appGood/" + skuIdStr;

//        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//        webView.getSettings().setJavaScriptEnabled(true);
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//适应内容大小

        webView.setWebChromeClient(new MyWebChromeClient());



        try {
            Logger.i("---------" + AppUtils.BASE_URL + "cservice?token=" + URLEncoder.encode(SharedPreferencesUtil.getLoginToken(), "UTF-8"));
            webView.loadUrl(AppUtils.BASE_URL + "cservice?token=" + URLEncoder.encode(SharedPreferencesUtil.getLoginToken(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }



    //同步获取token
    @JavascriptInterface
    public String getLoginUser(Object msg)  {
        String login_token = "";
        if (SharedPreferencesUtil.isLogin()){
            try {
                login_token = URLEncoder.encode(SharedPreferencesUtil.getLoginToken(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return  login_token;
    }



    private class MyWebChromeClient extends WebChromeClient{

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> valueCallback) {
            mUploadCallBack = valueCallback;
            showFileChooser();
        }

        // For Android  >= 3.0
        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
            mUploadCallBack = valueCallback;
            showFileChooser();
        }

        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
            mUploadCallBack = valueCallback;
            showFileChooser();
        }

        // For Android >= 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            mUploadCallBackAboveL = filePathCallback;
            showFileChooser();
            return true;
        }
    }


    private void showFileChooser(){
        sheetDialog =  new SheetDialog.Builder(OnlineCServiceActivity.this).setTitle(ConstantsUtils.EMPTY_STR)
                .addMenu("拍照", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()){
                            sheetDialog.dismiss();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            cameraPath = SDCardUtils.getSDCardPath() + "/temp.png";
                            File file = new File(cameraPath);
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(OnlineCServiceActivity.this, BuildConfig.APPLICATION_ID + ".provider", file));
                            }else{
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            }

                            intent.putExtra("return-data", false);
                            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
                            intent.putExtra("noFaceDetection", true);
                            startActivityForResult(intent, TAKE_CAMERA_PHOTO);
                        }
                    }
                })
                .addMenu("从相册中选择", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()){
                            sheetDialog.dismiss();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            startPickPhoto();
                        }
                    }
                }).setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        clearUploadMessage();
                        sheetDialog.dismiss();
                    }
                }).create();
        sheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                clearUploadMessage();
            }
        });
        sheetDialog.show();


    }

    //选择照片
    private void startPickPhoto(){

        PictureSelector.create((Activity) context)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
//                    .maxSelectNum(3)
                .maxSelectNum(1)
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(3)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(false)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .glideOverride(260, 260)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == TAKE_CAMERA_PHOTO){//拍照
//                ToastTools.showToast(OnlineCServiceActivity.this,"asdfasdf" + cameraPath);
                compressPictureUpload(cameraPath);
            }else if(requestCode == PictureConfig.CHOOSE_REQUEST){//选择照片

                // 图片选择结果回调
                List<LocalMedia> tempList = PictureSelector.obtainMultipleResult(data);
                for (LocalMedia media : tempList) {
                    Logger.i("图片-----》", media.getCompressPath());
                    upLoad(media.getCompressPath());
                }
//                ToastTools.showToast(OnlineCServiceActivity.this,"asddddddddddd");

            }
        }
    }


    //压缩并上传图片
    private Bitmap bitmap;
    private File uploadFile;
    private void compressPictureUpload(String imagePath){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        bitmap = BitmapFactory.decodeFile(imagePath, options);

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                uploadFile = compressImage(bitmap);
                emitter.onNext(uploadFile.getAbsolutePath());
            }
        }).subscribeOn(Schedulers.computation()).observeOn(Schedulers.newThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String temp) throws Exception {
                upLoad(temp);
                recycleBitmap(bitmap);
            }
        });
    }


    /**
     * 压缩图片（质量压缩）
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 5 * 1024 && options > 10) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            Logger.i("-----------------------------option:" + options);
            if (options > 0) {//options 的范围为0--100
                bitmap.compress(Bitmap.CompressFormat.PNG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            }
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                Logger.e(e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            Logger.e(e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }

    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps == null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }



    /*
     * 上传头像
     * */
    public void upLoad(String photoPath){


        File file = new File(photoPath);
        OkHttpClient okHttpClient = new OkHttpClient();


        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"),file);

        MultipartBody fileBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), requestBody)
                .build();

        Request request = new Request.Builder()
                .url(AppUtils.BASE_URL + "uuuuu/upload")
                .post(fileBody)
                .build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.e("OwnMessageActivity", "onFailure: "+e.getMessage() );
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                final BaseResultEntity baseResultEntity = gson.fromJson(string, BaseResultEntity.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){
                            String imgUrl = (String) baseResultEntity.getData();

                            imgUrl = "img[" + imgUrl + "]";
//                            Toast.makeText(OnlineCServiceActivity.this, "上传成功了" +imgUrl, Toast.LENGTH_SHORT).show();
//                            Map<String,String> map = new HashMap<>();
//                            map.put("userId","123");
//                            map.put("content",imgUrl);
                            Toast.makeText(OnlineCServiceActivity.this, "上传成功了" +imgUrl, Toast.LENGTH_SHORT).show();
                            webView.callHandler("sendImageAsyn",new Object[]{imgUrl},new OnReturnValue<Integer>(){
                                @Override
                                public void onValue(Integer retValue) {
                                    ToastTools.showToast(OnlineCServiceActivity.this,"发送成功");
                                }
                            });
                        }else {
                            Toast.makeText(OnlineCServiceActivity.this, baseResultEntity.getMsg()+"    "+baseResultEntity.getCode(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });
    }

    /**
     * webview没有选择文件也要传null，防止下次无法执行
     */
    private void clearUploadMessage() {
        if (mUploadCallBackAboveL != null) {
            mUploadCallBackAboveL.onReceiveValue(null);
            mUploadCallBackAboveL = null;
        }
        if (mUploadCallBack != null) {
            mUploadCallBack.onReceiveValue(null);
            mUploadCallBack = null;
        }
    }

    @Override
    protected void addListener() {

    }


    @OnClick(R.id.img_back)
    public void onBack(){

//        webView.callHandler("sendImageAsyn",new Object[]{"img[http://pic51.nipic.com/file/20141025/8649940_220505558734_2.jpg]"},new OnReturnValue<Integer>(){
//            @Override
//            public void onValue(Integer retValue) {
//                ToastTools.showToast(OnlineCServiceActivity.this,"发送成功");
//            }
//        });

       onBackPressed();
    }




    public static Intent getIntent(Context context,String keyword){
        Intent intent = new Intent(context, OnlineCServiceActivity.class);
        intent.putExtra(ARG_KEYWORD, keyword);
        return intent;
    }









}
